/**
 * @date 5:38:05 PM
 * StudentServiceImpl.java
 * Administrator
 * TODO
 */
package com.qs.education.service.impl;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.qs.education.bean.api.PageBean;
import com.qs.education.bean.api.ResponseBean;
import com.qs.education.bean.api.ResponseListBean;
import com.qs.education.bean.beans.EducationStudentResponse;
import com.qs.education.bean.entity.EducationClass;
import com.qs.education.bean.entity.EducationGrade;
import com.qs.education.bean.entity.EducationGroup;
import com.qs.education.bean.entity.EducationSchool;
import com.qs.education.bean.entity.EducationStudent;
import com.qs.education.bean.entity.EducationTeacher;
import com.qs.education.bean.enums.ResponseStatus;
import com.qs.education.bean.service.BaseService;
import com.qs.education.bean.utils.BeanCopyNotNull;
import com.qs.education.bean.utils.DateUtil;
import com.qs.education.bean.utils.GetNullProperties;
import com.qs.education.bean.utils.PasswordUtils;
import com.qs.education.bean.utils.TokenUtil;
import com.qs.education.service.IStudentAPIService;
/**
 * @class StudentServiceImpl	
 * @author Warren
 * @description
 * @date Oct 31, 2018 
 */
@Service
public class StudentAPIServiceImpl extends BaseService implements IStudentAPIService{
	
	/**
	 * @author Warren
	 * @param mobile
	 * @param password
	 * @return EducationStudentResponse
	 * @description 根据手机号码和密码查询学生实体
	 * @date Oct 31, 2018
	 */
	@Override
	public EducationStudentResponse getEducationStudent(Long id) {
		EducationStudent educationStudent = iEducationStudentDao.get(EducationStudent.class, id);
		EducationStudentResponse educationStudentBean = new EducationStudentResponse();
		if(educationStudent!= null) {
			BeanUtils.copyProperties(educationStudent, educationStudentBean);
			educationStudentBean.setStatus(ResponseStatus.SUCCESS.toString());
			return educationStudentBean;
		}
		educationStudentBean.setStatus(ResponseStatus.FAILED.toString());
		return educationStudentBean;
	}

	
	/**
	 * @author Warren
	 * @param student
	 * @return Map<String,Object>
	 * @description 学生用户注册
	 * @date Nov 5, 2018
	 */
	@Transactional
	@Override
	public ResponseBean register(EducationStudent educationStudent) {
		ResponseBean responseBean = new ResponseBean();
		educationStudent.setCreateDate(new Date());
		educationStudent.setCreateTime(new SimpleDateFormat("HH:mm:ss").format(new Date()));
		String md5Pass = PasswordUtils.encodPassword(educationStudent.getPassword());
		educationStudent.setPassword(md5Pass);
		Boolean result = iEducationStudentDao.save(educationStudent);
		if(result) {
			responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		}else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
		}
		return responseBean;
	}

	/**
	 * @author Warren
	 * @param mobile
	 * @param password
	 * @return EducationStudentResponse
	 * @description 学生登录
	 * @date Nov 6, 2018
	 */
	@Transactional
	@Override
	public EducationStudentResponse login(String mobile, String password) {
		String md5Pass = PasswordUtils.encodPassword(password);
		EducationStudent educationStudent = iEducationStudentDao.getEducationStudent(mobile, md5Pass);
		EducationStudentResponse educationStudentBean = new EducationStudentResponse();
		if(educationStudent!= null) {
			//设置token过期时间，暂且设置为20天。
			Date date = new Date(System.currentTimeMillis()+ 1000*60*60*24*20);
			String expirationDate = DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss");
			//获得token
			String token = TokenUtil.createToken(Long.toString(educationStudent.getId()), educationStudent.getName(), 
					md5Pass, expirationDate);
			
			educationStudent.setStuToken(token);
			//把token存到数据库相关记录中
			iEducationStudentDao.update(educationStudent);
			BeanUtils.copyProperties(educationStudent, educationStudentBean);
			educationStudentBean.setStatus(ResponseStatus.SUCCESS.toString());
			educationStudentBean.setMessage("登陆成功！");
		}else {
			educationStudentBean.setStatus(ResponseStatus.FAILED.toString());
			educationStudentBean.setMessage("账号或密码错误！");
		}
		return educationStudentBean;
	}


	/**
	 * @author Warren
	 * @param mobile
	 * @return ResponseBean
	 * @description 学生退出app端登录
	 * @date Nov 6, 2018
	 */
	@Transactional
	@Override
	public ResponseBean exit(String mobile) {
		ResponseBean responseBean = new ResponseBean();
		EducationStudent educationStudent = iEducationStudentDao.findEducationStudentByMobile(mobile);
		if(educationStudent !=null) {
			educationStudent.setStuToken(null);
			boolean result = iEducationStudentDao.update(educationStudent);
			if(result) {
				responseBean.setStatus(ResponseStatus.SUCCESS.toString());
				return responseBean;
			}
			responseBean.setStatus(ResponseStatus.FAILED.toString());
		}else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
		}
	
		return responseBean;
	}

	/**
	 * @author Warren
	 * @param mobile 手机号
	 * @param password 新密码
	 * @return ResponseBean
	 * @description 重置密码
	 * @date Nov 6, 2018
	 */
	@Transactional
	@Override
	public ResponseBean resetPwd(String mobile, String password) {
		ResponseBean responseBean = new ResponseBean();
		EducationStudent obj = iEducationStudentDao.findEducationStudentByMobile(mobile);
		obj.setMobile(mobile);
		String md5Pass = PasswordUtils.encodPassword(password);
		obj.setPassword(md5Pass);
		boolean result = iEducationStudentDao.update(obj);
		if(result) {
			responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		}else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
		}
		return responseBean;
	}

	/**
	 * @author Warren
	 * @param mobile
	 * @return ResponseBean
	 * @description 根据手机号查询是否已注册
	 * @date Nov 7, 2018
	 */
	@Override
	public ResponseBean mobileIsRepeat(String mobile) {
		ResponseBean responseBean = new ResponseBean();
		EducationStudent obj = iEducationStudentDao.findEducationStudentByMobile(mobile);
		if(obj !=null) {
			responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		}else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
		}
		return responseBean;
	}
	
	/**
	 * @author Warren
	 * @param educationStudentJSON
	 * @param file
	 * @param schoolId
	 * @param gradeId
	 * @param classId
	 * @param appAddress
	 * @return ResponseBean
	 * @description 修改学生信息
	 * @date Nov 20, 2018
	 */
	@Transactional
	@Override
	public ResponseBean updateStudentInfo(String educationStudentJSON,MultipartFile file,String schoolId,String gradeId,String classId,String appAddress) {
		ResponseBean responseBean = new ResponseBean();
		EducationStudent subjectStudent = JSONObject.parseObject(educationStudentJSON, EducationStudent.class);
		EducationStudent educationStudent = iEducationStudentDao.get(EducationStudent.class, subjectStudent.getId());
		try {
			BeanCopyNotNull.copyNotNullAndPrimitiveFiled(subjectStudent, educationStudent);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			responseBean.setStatus(ResponseStatus.FAILED.toString());
			return responseBean;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			responseBean.setStatus(ResponseStatus.FAILED.toString());
			return responseBean;
		}
		
		if(file!=null && !file.isEmpty()) {
			String oldImg = educationStudent.getHeadImage();
			if(oldImg!=null && !oldImg.equals("")) {
				String oldImgName = oldImg.substring(oldImg.lastIndexOf("/")+1);
				File oldFile = new File(configProperties.getImgsDiskPath() + oldImgName);
				if(oldFile.exists()) {
					oldFile.delete();
				}
			}
			String oldName = file.getOriginalFilename();
			int beginIndex = oldName.lastIndexOf(".");
			String suffix = oldName.substring(beginIndex);
			String newName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
			File newFile = new File(configProperties.getImgsDiskPath() + newName);
			try {
				file.transferTo(newFile);
				educationStudent.setHeadImage(appAddress + newName);
			} catch (IllegalStateException e) {
				e.printStackTrace();
				responseBean.setStatus(ResponseStatus.FAILED.toString());
				return responseBean;
			} catch (IOException e) {
				e.printStackTrace();
				responseBean.setStatus(ResponseStatus.FAILED.toString());
				return responseBean;
			}
		}
		
		if(schoolId!= null && !schoolId.equals("")) {
			EducationSchool educationSchool = iEducationSchoolDao.get(EducationSchool.class, Long.parseLong(schoolId));
			educationStudent.setSchool(educationSchool);
		}
	
		if(gradeId!= null && !gradeId.equals("")) {
			EducationGrade educationGrade = iEducationGradeDao.get(EducationGrade.class, Long.parseLong(gradeId));
			educationStudent.setGrade(educationGrade);
		}
		
		if(classId!= null && !classId.equals("")) {
			EducationClass educationClass = iEducationClassDao.get(EducationClass.class, Long.parseLong(classId));
			educationStudent.setClazz(educationClass);
		}
		
		boolean result = iEducationStudentDao.update(educationStudent);
		if(result) {
			responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		}else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
		}
		return responseBean;
	}
	
	/**
	 * @author Warren
	 * @param mobile 手机号
	 * @param oldPassword 原密码
	 * @param newPassword 新密码
	 * @return ResponseBean
	 * @description 修改密码
	 * @date Nov 20, 2018
	 */
	@Transactional
	@Override
	public ResponseBean changePwd(String mobile, String oldPassword, String newPassword) {
		ResponseBean responseBean = new ResponseBean();
		if(mobile == null || mobile.equals("") || oldPassword == null || oldPassword.equals("") || newPassword == null || newPassword.equals("")) {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
			responseBean.setMessage("手机号、旧密码、新密码格式不正确。");
			return responseBean;
		}
		
		String md5OldPassword = PasswordUtils.encodPassword(oldPassword);
		EducationStudent educationStudent = iEducationStudentDao.getEducationStudent(mobile, md5OldPassword);
		if(educationStudent==null) {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
			responseBean.setMessage("手机号或旧密码错误。");
			return responseBean;
		}
		String md5NewPassword = PasswordUtils.encodPassword(newPassword);
		educationStudent.setPassword(md5NewPassword);
		boolean result = iEducationStudentDao.save(educationStudent);
		if(result) {
			responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		}else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
			responseBean.setMessage("服务器发生错误，请重新修改");
		}
		return responseBean;
	}
	
	/**
	 * @author Warren
	 * @param groupId 
	 * @param studentId
	 * @return ResponseBean
	 * @description 学生主动退出班群
	 * @date Nov 20, 2018
	 */
	@Transactional
	@Override
	public ResponseBean exitGroup(Long groupId, Long studentId) {
		ResponseBean responseBean = new ResponseBean();
		EducationGroup group = iEducationGroupDao.get(EducationGroup.class, groupId);
		List<EducationStudent> students = group.getStudents();
		EducationStudent student = iEducationStudentDao.get(EducationStudent.class,studentId);
		students.remove(student);
		boolean result = iEducationGroupDao.update(group);
		if(result) {
			responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		}else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
		}
		return responseBean;
	}
	
//----------------------------------------------------------------------------------------------------------------------
	@Override
	public PageBean getEducationStudent(EducationStudent educationStudent,Integer currentPage, Integer pageSize) {

		int recordCount = iEducationStudentDao.getStudentCount(educationStudent);
		List<EducationStudent> list = iEducationStudentDao.getStudent(educationStudent,currentPage,pageSize);
		PageBean pagePean = new PageBean(currentPage, pageSize, recordCount, list);
		
		return pagePean;
	}


	@Override
	@Transactional
	public Boolean deleteStudentyId(Long studentId) {
		
		return iEducationStudentDao.delete(studentId, EducationStudent.class);
	}


	@Override
	public EducationStudentResponse findStudentById(Long studentId) {
		
		EducationStudent educationStudent = iEducationStudentDao.get(EducationStudent.class, studentId);
		EducationStudentResponse response = new EducationStudentResponse();
		if (educationStudent!=null) {
			BeanUtils.copyProperties(educationStudent, response);
		}
		
		return response;
	}


	@Override
	@Transactional
	public Boolean updateStudent(EducationStudent newStudent) {
		
		String[] ignoreProperties = GetNullProperties.getNullProperties(newStudent);
		System.out.println(ignoreProperties);
		EducationStudent oldStudent = iEducationStudentDao.get(EducationStudent.class, newStudent.getId());
		BeanUtils.copyProperties(newStudent, oldStudent, ignoreProperties);
		if (oldStudent.getClazz()!=null && oldStudent.getClazz().getId()==null) {
			oldStudent.setClazz(null);
		}
		if (oldStudent.getSchool()!=null && oldStudent.getSchool().getId()==null) {
			oldStudent.setSchool(null);
		}
		if (oldStudent.getGrade()!=null && oldStudent.getGrade().getId()==null) {
			oldStudent.setGrade(null);
		}
		
		return iEducationStudentDao.merge(oldStudent);
	}


	@Override
	@Transactional
	public Boolean addStudent(EducationStudent student) {
		
		if (student.getClazz()!=null&&student.getClazz().getId()==null) {
			student.setClazz(null);
		}
		if (student.getSchool()!=null&&student.getSchool().getId()==null) {
			student.setSchool(null);
		}
		if (student.getGrade()!=null&&student.getGrade().getId()==null) {
			student.setGrade(null);
		}
		student.setCreateDate(new Date());
		student.setCreateTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
		student.setPassword(PasswordUtils.encodPassword(student.getPassword()));
		
		return iEducationStudentDao.save(student);
	}


	@Override
	public ResponseListBean<EducationStudent> findStudentByCondition(EducationStudent student) {
		
		List<EducationStudent> list = iEducationStudentDao.findStudentByCondition(student);
		ResponseListBean<EducationStudent> responseList = new ResponseListBean<>();
		responseList.setList(list);
		
		return responseList;
	}


}
